package com.useeinfo.oa.modules.inspection.dao;

import com.useeinfo.framework.extend.dao.CrudDao;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.QueryUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.inspection.entity.FacilityInspectionSnap;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository("facilityInspectionSnapDao")
public class FacilityInspectionSnapDao implements CrudDao<FacilityInspectionSnap> {
    private final static Logger logger = LoggerFactory.getLogger(FacilityInspectionSnapDao.class);

    @PersistenceContext
    private EntityManager entityManager;

    public List<FacilityInspectionSnap> findByFacilityId(Long facilityId, String  serial) {
        List<FacilityInspectionSnap> facilityInspectionSnapList = this.entityManager.createQuery("select fm from FacilityInspectionSnap fm where fm.deleteStatus = false and fm.serial = :serial and fm.facilityId = :facilityId" , FacilityInspectionSnap.class)
                .setParameter("serial", serial)
                .setParameter("facilityId",facilityId).getResultList();
        if (CollectionUtils.isEmpty(facilityInspectionSnapList)) {
            return null;
        }
        return facilityInspectionSnapList;
    }



    @Override
    public Map<String, Object> getSearchCondition(Map<String, String> queryHash) {
        Map<String, Object> conditionHash = new HashMap<>();
        conditionHash.put("s.deleteStatus = ?{paramIndex} ", false);
        if (queryHash == null || queryHash.size() == 0) {
            return conditionHash;
        }
        String inspectionOrderId = queryHash.get("inspectionOrderId");
        if (!StringUtils.isEmpty(inspectionOrderId)) {
            conditionHash.put("(s.inspectionOrder.id = ?{paramIndex}) ", StringConverters.null2Long(inspectionOrderId));
        }
        String facilityId = queryHash.get("facilityId");
        if (!StringUtils.isEmpty(facilityId)) {
            conditionHash.put("(s.facilityId = ?{paramIndex}) ", StringConverters.null2Long(facilityId));
        }
        String serial = queryHash.get("serial");
        if (!StringUtils.isEmpty(serial)) {
            conditionHash.put("(s.serial = ?{paramIndex}) ", serial);
        }
        return conditionHash;
    }

    @Override
    public Long totalRecord(Map<String, String> queryHash) {
        Map<String, Object> conditions = getSearchCondition(queryHash);
        TypedQuery<Long> typedQuery = QueryUtils.getTypedQueryByCondition("select count(s) from FacilityInspectionSnap s ", conditions, entityManager, Long.class);
        return typedQuery.getSingleResult();
    }

    @Override
    public List<FacilityInspectionSnap> findList(QueryParam queryParam) {
        String sqlInfo = queryParam.joinJPQL("select s from FacilityInspectionSnap s ", "order by s.id desc ");
        Map<String, Object> conditions = getSearchCondition(queryParam.getSqlMap());
        TypedQuery<FacilityInspectionSnap> typedQuery = QueryUtils.getTypedQueryByCondition(sqlInfo, conditions, entityManager, FacilityInspectionSnap.class);
        return queryParam.findPageList(typedQuery);
    }

    @Override
    public FacilityInspectionSnap findModel(Long id) {
        return entityManager.find(FacilityInspectionSnap.class, id);
    }

    @Override
    public Integer add(FacilityInspectionSnap model) {
        model.setCreateDate(new Date());
        entityManager.persist(model);
        logger.info("FacilityInspectionSnapDaoImpl添加facilityInspectionSnap成功！");
        return 1;
    }

    @Override
    public Integer update(FacilityInspectionSnap model) {
        model.setUpdateDate(new Date());
        entityManager.merge(model);
        return 1;
    }

    @Override
    public Integer delete(Long id) {
        FacilityInspectionSnap facilityInspectionSnap = entityManager.find(FacilityInspectionSnap.class, id);
        entityManager.remove(facilityInspectionSnap);
        return 1;
    }

    @Override
    public Integer deleteLogic(FacilityInspectionSnap model) {
        model.setDeleteStatus(true);
        return 1;
    }

    public List<Object[]> completePercent(String enterpriseIds,String startDate,String endDate,boolean completed,String rootCatId) {
        String str1 = "";
        if(completed){
            str1 = " AND complete = TRUE ";
        }
        String str2 = "";
        if(StringUtils.isNotBlank(rootCatId)){
            str2 = " AND root_cat_id ="+rootCatId+" ";
        }
        String sql = "SELECT root_cat_id,COUNT(*) FROM facility_inspection_snap \n" +
                "WHERE inspection_order_id IN (SELECT id FROM inspection_order WHERE delete_status = FALSE AND enterprise_id IN ("+enterpriseIds+") AND end_date_time BETWEEN '"+startDate+"' AND '"+endDate+"' "+str1+") "+str2+"  \n" +
                "GROUP BY root_cat_id";
        logger.info("sql语句为：" + sql);
        Query query = this.entityManager.createNativeQuery(sql);
        List<Object[]> queryResultList = query.getResultList();
        return queryResultList;
    }
}
